import pymysql, random
from DBUtils.PooledDB import PooledDB
import asyncio


class Db:
    db_host = "localhost"
    db_username = "root"
    db_pwd = ""
    db_charset = "utf8"
    db_name = "test"
    pools = None
    cursor = None
    conn = None

    def __init__(self):
        self.pools = PooledDB(creator=pymysql, host=self.db_host, user=self.db_username, passwd=self.db_pwd,
                              db=self.db_name, port=3306, charset=self.db_charset, maxconnections=50, blocking=True)

    def query(self, sql):
        self.conn = self.pools.connection()
        self.cursor = self.conn.cursor()

    def close(self):
        self.cursor.close()
        self.conn.close()


def query(db, i):
    # sql = r"select count(*) from tb_curl_log"
    sql = "insert into tb_collection_user_rank(`user_id`,`order_id`,`rank`,`collection_id`,`version`,`created_at`,`updated_at`) value({0},{1},{2},{3},{4},{5},{6})".format(
        i, i, i, i, 88, 0, 0)
    conn = db.pools.connection()
    cursor = conn.cursor()
    r = cursor.execute(sql)
    conn.commit()
    # result = cursor.fetchall()
  
    # print("rand:" + str(rand))
    print("i:" + str(i))

if __name__ == "__main__":

    queue = Queue()
    i = 0
    db = Db()
    spans = tasks = []
    pools = Pool(500)

    while i <= 100000:
        spans.append(pools.spawn(query, db, i))
        i += 1

    gevent.joinall(spans)

